<template>
  <div>
    <a-form
      ref="manaPlanFormRef"
      class="mana-plan-form"
      :label-col="{ style: { width: '105px' } }"
      :disabled="isPushed"
      :model="updatedData"
    >
      <div class="mana-plan-item-info" v-for="(item, index) in updatedData" :key="index">
        <div
          style="
            display: flex;
            place-content: center space-between;
            margin-bottom: 10px;
            border-bottom: 1px solid #e8e8e8;
          "
        >
          <a-form-item label="提醒时间" :rules="[{ required: true, message: '请输入提醒时间' }]">
            <div style="display: flex; align-items: center">
              每
              <a-input-number
                style="margin: 0 8px"
                :min="1"
                :precision="0"
                v-model:value="item.cronCycle"
              />
              天提醒一次
            </div>
          </a-form-item>
          <a-button type="link" danger @click="removePlanItem(index)"> 删除 </a-button>
        </div>
        <div>
          <a-form-item label="当前模板库">
            <div style="display: flex; align-content: center">
              <a-space :size="[0, 0]">
                <span
                  @click="changeTemplate(item, '公共模板')"
                  :class="
                    item.templateAffiliation == '公共模板'
                      ? 'template-col template-col-active'
                      : 'template-col'
                  "
                  >健康宣教模板库</span
                >
                <span
                  @click="changeTemplate(item, '个人模板')"
                  :class="
                    item.templateAffiliation == '个人模板'
                      ? 'template-col template-col-active'
                      : 'template-col'
                  "
                  >个人模板库</span
                >
              </a-space>
            </div>
          </a-form-item>
          <a-form-item label="选择模板" :rules="[{ required: true, message: '选择模板' }]">
            <a-select
              v-model:value="item.templateId"
              placeholder="请选择模板"
              :options="item.templateList"
              @change="templateChange(item, $event, index)"
              showSearch
            />

            <a-button type="link" @click="showIndividual(item)"
              >保存当前已修改方案到个人模板</a-button
            >
          </a-form-item>
        </div>
        <a-form-item label="知识库标签" :rules="[{ required: true, message: '请选择知识库标签' }]">
          <a-select
            mode="multiple"
            v-model:value="item.contents"
            :options="propagandaLabelsData"
            showSearch
            allowClear
            placeholder="请选择知识库标签"
            style="width: 100%"
          />
        </a-form-item>
      </div>
      <a-button
        @click="addPlanItem"
        :icon="h(PlusOutlined)"
        type="primary"
        ghost
        v-if="!isPushed"
        class="add-plan-item"
      >
        添加
      </a-button>
    </a-form>

    <!-- 个人模板保存 -->
    <a-modal
      v-model:open="individualOpen"
      title="保存当前方案到个人模板"
      :maskClosable="false"
      :destroyOnClose="true"
    >
      <a-form ref="individualForm" :model="individualFormData" style="margin-top: 14px">
        <div style="margin-bottom: 16px; font-weight: bold">{{ individualName }}</div>
        <a-form-item
          name="templateName"
          :rules="[{ required: true, message: '请输入模板名称', whitespace: true }]"
        >
          <a-auto-complete
            style="width: 100%"
            placeholder="请输入模板名称"
            :options="individualTemplateList"
            v-model:value="individualFormData.templateName"
            :filterOption="
              (inputValue, option) =>
                option.value.toUpperCase().indexOf(individualFormData.templateName.toUpperCase()) >=
                0
            "
            @blur="
              (value) => {
                individualFormData.templateName = individualFormData.templateName.replace(
                  /\s+/g,
                  ''
                )
              }
            "
          />
          <span
            v-if="
              individualTemplateList.findIndex((item) => {
                return item.value === individualFormData.templateName
              }) >= 0
            "
            style="color: red"
            >您当前选择的是已存在的模板，保存将覆盖原有模板内容</span
          >
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="individualOpen = false">取消</a-button>
        <a-button type="primary" @click="saveIndividual">保存</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, h, defineEmits, watchEffect } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import store from '@/store'
import { getTemplateDetailList, TemplateAddOrUpdate } from '@/api/healthManaWorkbench/index'
import { message } from 'ant-design-vue'
import { getTags } from '@/api/template.ts'
const manaPlanFormRef = ref()
const props = defineProps<{
  isPushed: boolean
  propagandaData: any[]
}>()

const userId = ref()
const templateDataList = ref()

// 模板
const individualTemplateList = ref()
const individualOpen = ref<boolean>(false)
const individualName = ref<string>('')
const individualFormData = reactive({
  templateName: '',
  templateType: '',
  content: '',
  data: {}
})

const emit = defineEmits(['update:propagandaData'])

const updatedData = ref<any>([])
const propagandaLabelsData = ref([])
onMounted(async () => {
  userId.value = store.userApp.userInfo.id

  templateDataList.value = await getTemplateList(null, null)

  await getTags().then(async (res) => {
    res.data.map((item) => {
      item.label = item.dictLabel
      item.value = item.dictLabel
    })
    propagandaLabelsData.value = res.data
  })

  nextTick(() => {
    updatedData.value = [...props.propagandaData]
  })
})

watchEffect(() => {
  if (props.propagandaData && props.propagandaData.length > 0) {
    updatedData.value = [...props.propagandaData]
  }
})

const removePlanItem = (index: any) => {
  updatedData.value.splice(index, 1) // 删除指定项
  updatedData.value = [...updatedData.value]
  emit('update:propagandaData', updatedData.value)
}

// 模板切换
const changeTemplate = (data, type) => {
  if (props.isPushed) {
    return
  } else {
    if (data.templateAffiliation == type) {
      //
    } else {
      data.templateAffiliation = type

      data.templateList = templateDataList.value.filter((tem) => {
        if (type == '个人模板') {
          return (
            tem.templateType == data.templateType &&
            tem.templateAffiliation == type &&
            tem.creator == userId.value
          )
        }
        return tem.templateType == data.templateType && tem.templateAffiliation == type
      })

      if (data.oldTemplateAffiliation != type) {
        data.templateId = data.templateList.length > 0 ? data.templateList[0].id : undefined
      } else {
        data.templateId = data.oldTemeplateId
      }

      const temData: any = data.templateList.find((tem) => {
        return tem.id == data.templateId
      })
      data.content = temData ? temData.content : ''
    }
  }
}

const addPlanItem = () => {
  updatedData.value.push({
    templateAffiliation: '公共模板',
    cronCycle: '',
    content: undefined,
    contents: [],
    templateId: undefined,
    templateType: '健康宣教',
    templateList: templateDataList.value.filter((tem) => {
      return tem.templateType == '健康宣教' && tem.templateAffiliation == '公共模板'
    })
  })
  console.log(updatedData.value)
  emit('update:propagandaData', updatedData.value)
}

// 选择模板切换
const templateChange = (data, e, index) => {
  // 根据选择的模板更新内容
  const selectedTemplate = data.templateList.find((tem) => tem.id == e)
  const content = selectedTemplate.content
  if (content) {
    if (typeof content === 'string' && content.trim().startsWith('[')) {
      data.contents = JSON.parse(content)
    } else {
      data.contents = [content]
    }
  }
  data.content = selectedTemplate ? selectedTemplate.content : ''
  data.templateId = e

  updatedData.value[index] = { ...data }

  emit('update:propagandaData', updatedData.value)
}

// 展示个人模板保存
const showIndividual = (data) => {
  // 模板类型判断
  if (!data.content) {
    message.error('健康宣教方案请填写完整')
  } else {
    individualTemplateList.value = []
    nextTick(() => {
      individualOpen.value = true
      if (individualForm.value) {
        individualForm.value.resetFields()
      }
      individualFormData.templateName = ''
      individualName.value = '健康宣教个人模板库'
      individualFormData.templateType = '健康宣教'
      individualFormData.content = data.content
      individualFormData.data = data // 需要保存的模板数据
      const listData = templateDataList.value.filter((tem) => {
        return (
          tem.templateType == '健康宣教' &&
          tem.templateAffiliation == '个人模板' &&
          tem.creator == userId.value
        )
      })
      listData.forEach((item) => {
        individualTemplateList.value.push({
          value: item.templateName,
          label: item.templateName
        })
      })
    })
  }
}

// 个人模板保存
const individualForm = ref()
const saveIndividual = () => {
  individualForm.value.validate().then(() => {
    // 对应模板类型的所有个人模板数据
    const templateData = templateDataList.value.filter((tem) => {
      return (
        tem.templateType == individualFormData.templateType &&
        tem.templateAffiliation == '个人模板' &&
        tem.creator == userId.value
      )
    })
    const temContent = individualFormData.data.content
    individualFormData.templateName = individualFormData.templateName.replace(/\s+/g, '')
    const data = {
      id: null,
      templateName: individualFormData.templateName,
      templateType: individualFormData.templateType,
      content: temContent,
      templateAffiliation: '个人模板',
      platformId: store.userStore.platformId
    }
    if (templateData.length > 0) {
      const someData = templateData.filter((item) => {
        return item.templateName === individualFormData.templateName
      })
      data.id = someData.length > 0 ? someData[0].id : null
    }
    TemplateAddOrUpdate(data).then(async (res) => {
      individualOpen.value = false
      templateDataList.value = await getTemplateList(null, null)
      updatedData.value.map((item) => {
        item.templateList = templateDataList.value.filter((tem) => {
          return (
            tem.templateType == individualFormData.templateType &&
            tem.templateAffiliation == '个人模板' &&
            tem.creator == userId.value
          )
        })
      })
      message.success('保存成功')
      emit('update:propagandaData', updatedData.value)
    })
  })
}

// 根据方案类型 模板类型获取响应的列表
const getTemplateList = async (templateType, templateAffiliation) => {
  let data: any = []
  const res = await getTemplateDetailList({
    templateType: templateType,
    templateAffiliation: templateAffiliation,
    platformId: store.userStore.platformId
  })

  res.data.map((item: any) => {
    item.label = item.templateName
    item.value = item.id
  })
  data = res.data
  return data
}
</script>
<style lang="less" scoped>
.mana-plan-item-info {
  padding: 16px 0;
  margin-bottom: 16px;
  border: 1px solid #e5e5e5;
}

.mana-plan-form .ant-form-item {
  padding-left: 24px;
  margin-bottom: 12px;
}

.mana-plan-form .sprot-form .ant-form-item {
  margin-bottom: 18px;
}

.template-col {
  padding: 6px 20px;
  cursor: pointer;
  border: 1px solid #e5e5e5;
  border-radius: 2px;
}

.template-col.template-col-active {
  color: #165dff;
  background: #e8f3ff;
  border: 1px solid #165dff;
  border-radius: 2px 0 0 2px;
}
</style>
